package org.example;


import io.socket.client.IO;

import io.socket.client.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

import static org.example.App.count;


/**
 * @author zhangjg
 * @desc
 * @date 2023/05/04 14:57
 **/
public class Client {

    private static final Logger logger = LoggerFactory.getLogger(Client.class);
    int num;

    public Client(int num){
        this.num = num;
    }

    public  Socket init() {
        Socket socket = null;
        // 服务端socket.io连接通信地址
        String url = "http://localhost:8092";
        try {
            IO.Options options = new IO.Options();
            options.path = "/socket.io";
            options.transports = new String[]{"websocket","xhr-polling","jsonp-polling"};
            // 失败重试次数
            options.reconnectionAttempts = 3;
            // 失败重连的时间间隔
            options.reconnectionDelay = 1000;
            // 连接超时时间(ms)
            options.timeout = 10000;
            options.upgrade = true;
            //final Socket socket = IO.socket(url + "?userId=2", options);
            socket = IO.socket(url+ "?userId=user_"+count.incrementAndGet(), options);

            // 自定义事件`connect` -> 接收服务端成功连接消息
            socket.on(Socket.EVENT_CONNECT, objects -> logger.info("连接成功: "+ num));
            // 自定义事件`disconnect` -> 接收服务端成功连接消息
            socket.on(Socket.EVENT_DISCONNECT, objects -> logger.info("已下线:" + Arrays.toString(objects)));
            // 自定义事件`connect_error` -> 接收服务端成功连接消息
            socket.on(Socket.EVENT_CONNECT_ERROR, objects -> logger.info("连接失败: "+num+" " + Arrays.toString(objects)));

            socket.connect();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return socket;
    }

}
